import 'dart:collection';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_edit_callback_widget/common_edit_callback_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_list_page_widget/common_list_page_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_search_bar_widget/common_search_bar_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_single_choice_button_widget/common_single_choice_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_sliver_delegate/common_sliver_delegate.dart';
import 'package:e_reception_flutter/common_widgets/common_title_edit_with_underline_widget/typeof/common_title_edit_with_underline_typeof.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/department_or_class_list_response.dart';
import 'package:e_reception_flutter/ui/company/company_detail/class_or_department/class_or_department_page.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/rich_text_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';

import 'bean/department_response_bean.dart';

class MultiSelectDepartmentWidget extends StatefulWidget {
  final List<String> selectIds;
  final String departmentType;

  const MultiSelectDepartmentWidget(
      {Key key, this.departmentType = "00", this.selectIds})
      : super(key: key);

  @override
  _MultiSelectDepartmentWidgetState createState() =>
      _MultiSelectDepartmentWidgetState();

  ///跳转方法
  static Future<EditTextAndValue> navigatorPush(BuildContext context,
      {List selectIds, bool multiSelect}) {
    print("zxx: selectedId---$selectIds");

    return RouterUtils.routeForFutureResult<EditTextAndValue>(
      context,
      MultiSelectDepartmentWidget(
        selectIds: selectIds,
      ),
    )..then((value) {
        print("返回值：${value}");
      });
  }
}

class _MultiSelectDepartmentWidgetState
    extends State<MultiSelectDepartmentWidget> {
  bool isLightUp = false;
  String mDepartmentText;
  List<String> selectIds;
  List<String> cacheIds;

  List<DepartmentOrClassListItemBean> dataList;

  List<DepartmentOrClassListItemBean> selectDataList = [];

  CommonListPageWidgetState<DepartmentOrClassListItemBean, DepartmentOrClassListResponse> _mState;

  ///搜索关键字
  String keyword;

  String cacheKey;

  void setCommonListState(
      CommonListPageWidgetState<DepartmentOrClassListItemBean, DepartmentOrClassListResponse> state) {
    _mState = state;
  }

  @override
  void initState()  {
    super.initState();
    selectIds = widget.selectIds ??[];

    cacheKey=KEY_SELECT_DEPARTMENT +
        UserRepository.getInstance().getCacheKeySuffix();
    SharePreferenceUtil.getStringList(cacheKey
        ).then((value) {
      cacheIds =value;
      if(cacheIds!=null){
        setState(() {

        });
      }
    });
    dataList = List();
  }

  @override
  Widget build(BuildContext context) {
    return CustomAnnotatedRegion(
      Scaffold(
        // resizeToAvoidBottomInset: false,
        // resizeToAvoidBottomPadding: false,
        backgroundColor:
            ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        body: CommonPackUpKeyboardWidget(
          child: Column(
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              _toTopBarWidget(),
              Expanded(
                child: NestedScrollView(
                  headerSliverBuilder: (context, bool) {
                    return [
                      SliverPersistentHeader(
                        delegate: CommonSliverPersistentHeaderDelegate(
                            child: Container(
                              padding: EdgeInsets.symmetric(vertical: 10),
                              color: ThemeRepository.getInstance()
                                  .getCardBgColor_21263C(),
                              child: CommonSearchBarWidget(
                                hintText: "搜索",
                                onChanged: (keyword) {
                                  this.keyword = keyword;
                                  _mState.viewModel.refresh();
                                },
                                onSubmitted: (keyword) {
                                  this.keyword = keyword;
                                  _mState.viewModel.refresh();
                                },
                              ),
                            ),
                            maxHeight: 50,
                            minHeight: 50),
                      )
                    ];
                  },
                  body: _toCustomListWidget(),
                ),
              ),
            ],
          ),
        ),
      ),
      navigationBarColor:
          ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
    );
  }

  //封装的列表
  Widget _toCustomListWidget() {
    return CommonListPageWidget<DepartmentOrClassListItemBean, DepartmentOrClassListResponse>(
      enablePullUp: false,
      enablePullDown: false,
      queryMapFunc: (int page) => {
        'authId': UserRepository.getInstance().authId,
        "current": 1,
        "size": '100',
        "type": '00',
        "searchName": keyword ?? ''
      },
      parseDataFunc: (VgHttpResponse resp) {
        DepartmentOrClassListResponse response =
        DepartmentOrClassListResponse.fromMap(resp?.data, ClassOrDepartmentPage.TYPE_DEPARTMENT);

        if (response != null &&
            response.success &&
            response.data != null &&
            response.data.page != null &&
            response.data.page.records != null) {
          if (cacheIds != null && cacheIds.length > 0) {
            List<DepartmentOrClassListItemBean> newList = List();
            response.data.page.records.forEach((element) {
              if (cacheIds.contains(element.departmentid)) {
                newList.insert(0, element);
              } else {
                newList.add(element);
              }
            });
            response.data.page.records = newList;
          }
        }
        return response;
      },
      physics: BouncingScrollPhysics(),
      itemBuilder: (BuildContext context, int index, DepartmentOrClassListItemBean itemBean) {
        return _toListItemWidget(context, index, itemBean);
      },
      //分割器构造器
      separatorBuilder: (context, int index, _) {
        return Container(
          height: 0,
          color: ThemeRepository.getInstance().getCardBgColor_21263C(),
          padding: const EdgeInsets.only(left: 15),
          child: Container(
            color: Color(0xFF303546),
          ),
        );
        // return divider;
      },
      netUrl:NetApi.DEPARTMENT_OR_CLASS_LIST,
      httpType: VgHttpType.post,
      stateFunc: (CommonListPageWidgetState<DepartmentOrClassListItemBean, DepartmentOrClassListResponse>
          state) {
        _mState = state;
      },
      listFunc: (List<DepartmentOrClassListItemBean> list) {
        dataList = list;
        if((selectDataList?.length??0)==0){
          dataList?.forEach((element) {
            if(selectIds?.toString()?.contains(element?.departmentid)){
              selectDataList?.add(element);
            }
          });
        }
      },
    );
  }

  Widget _toListItemWidget(
      BuildContext context, int index, DepartmentOrClassListItemBean itemBean) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        //判断字体是否选中
        // departmentText =
        if (selectIds.contains(itemBean.departmentid)) {
          selectDataList?.remove(itemBean);
          selectIds.remove(itemBean.departmentid);
        } else {
          if((selectDataList?.length??0)!=0){
            List<String> ids = [];
            selectDataList?.forEach((element) {
              ids?.add(element?.departmentid);
            });
            if(!(ids?.toString()?.contains(itemBean?.departmentid))){
              selectDataList?.add(itemBean);
            }
          }else selectDataList?.add(itemBean);
          selectIds.add(itemBean.departmentid);
        }
        setState(() {});
      },
      child: Container(
        color: Color(0xFF21263C),
        height: 60,
        alignment: Alignment.centerLeft,
        padding: const EdgeInsets.symmetric(horizontal: 15),
        child: Row(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(right: 10),
              child: CommonSingleChoiceButtonWidget(
                  (selectIds.contains(itemBean?.departmentid??""))
                      ? CommonSingleChoiceStatus.selected
                      : CommonSingleChoiceStatus.unSelect),
            ),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(
                    height: 10,
                  ),
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          itemBean?.department ?? "",
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: Color(0xFFD0E0F7),
                            // color: (selectIds.contains(itemBean.departmentid))
                            //     ? Color(0xFF1890FF)
                            //     : Color(0xFFD0E0F7),
                            fontSize: 15,
                          ),
                        ),
                      ),
                      Visibility(
                        visible: (itemBean?.adminCnt??0) > 0,
                        child: Padding(
                          padding: const EdgeInsets.only(top: 1),
                          child: Row(
                            children: [
                              ConstrainedBox(
                                constraints: BoxConstraints(maxWidth: 80),
                                child: Text(
                                  '管理员：${(itemBean?.adminCnt??0) == 0 ? '' : ((itemBean?.adminCnt??0) > 1 ? '${itemBean.adminName.substring(0, itemBean.adminName.indexOf(',')) ?? ''}' : itemBean.adminName ?? '0')}',
                                  style: TextStyle(
                                    fontSize: 10,
                                    color: Color(0xff5e687c),
                                  ),
                                  maxLines: 1,
                                ),
                              ),
                              Text(
                                '${(itemBean?.adminCnt??0) == 0 ? '' : ((itemBean?.adminCnt??0) > 1 ? '等${(itemBean?.adminCnt??0)}人' : '')}',
                                style: TextStyle(
                                  fontSize: 10,
                                  color: Color(0xff5e687c),
                                ),
                                maxLines: 1,
                              )
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                  SizedBox(
                    height: 1,
                  ),
                  RichTextWidget(
                    fontSize: 12,
                    contentMap: LinkedHashMap.from({
                      '成员': Color(0xff5e687c),
                      '${itemBean?.memberCnt??0}': (itemBean?.memberCnt ?? 0) > 0
                          ? ThemeRepository.getInstance()
                              .getPrimaryColor_1890FF()
                          : Color(0xff5e687c),
                      '人': Color(0xff5e687c)
                    }),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "部门",
      rightWidget: _buttonWidget(),
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
    );
  }

  Widget _buttonWidget() {
    return Container(
      child: CommonFixedHeightConfirmButtonWidget(
        isAlive: true,
        width: 48,
        height: 24,
        unSelectBgColor:
            ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
        selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        unSelectTextStyle: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 12,
            fontWeight: FontWeight.w600),
        selectedTextStyle: TextStyle(
            color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
        text: "确定",
        onTap: () {
          //提交按钮
          _pop();
        },
      ),
    );
  }

  ///返回部门选中值
  void _pop() {
    // StringBuffer ids=StringBuffer();
    StringBuffer names = StringBuffer();
    // selectIds.forEach((e) => ids.write(e+","));
    List<DepartmentOrClassListItemBean> newSelectDataList = [];
    List<String> ids = [];
    if((selectDataList?.length??0)!=0){
      selectDataList?.forEach((element) {
        ids?.add(element?.departmentid);
        newSelectDataList?.add(element);
      });
    }
    if((dataList?.length??0)!=0){
      dataList?.forEach((element) {
        if(!(ids?.toString()?.contains(element?.departmentid))){
          newSelectDataList?.add(element);
        }
      });
    }
    newSelectDataList.forEach((element) {
      if (selectIds.contains(element.departmentid)) {
        names.write(element.department + "、");
      }
    });
    String name = names.toString();
    if (name.length > 1) {
      name = name.substring(0, names.length - 1);
    }
    SharePreferenceUtil.putStringList(cacheKey, selectIds);
    RouterUtils.pop(context,
        result: EditTextAndValue(value: selectIds, editText: name));
  }
}
